<script setup>
import SchedulingFrame from '../components/SchedulingFrame.vue';
import { storeToRefs } from 'pinia';
import { useItem } from '../../store/index.js';
import { createCronJobHandler as createItem, updateCronJobHandler as updateItem } from '../../api/cronjob.js';
import { ElMessage,ElMessageBox  } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import { ref ,onBeforeMount, reactive, toRefs} from 'vue';
import StringOrNumber from '../components/StringOrNumber.vue'
import { da } from 'element-plus/es/locales.mjs';
import {useRouter} from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  resourceType: {
    type: String,
    default: 'CronJob'
  },
  cronJobItem:{
    type: Object
  }
})
const useItemer = useItem()
const showDetail = ref(false)
let yamlContent = ref('')
const submitRollback = (msg)=>{ 
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '继续编辑',
      type: 'success',
    }
  )
    .then(() => {
      //跳转到对应的列表页
      router.replace({
        path: '/cronjob/list',
        query: {
          clusterId: useItemer.clusterId,
          namespace: useItemer.namespace,
          
        }
      })
    })
    .catch(() => {
      router.replace({
        path: '/cronjob/edit',
        query: {
          clusterId: useItemer.clusterId,
          namespace: useItemer.namespace,
          name: useItemer.item.metadata.name,
          method: "Update"
        }
      })
    })
}
const data = reactive({
  cronjobItem: {
    apiVersion: "batch/v1",
    kind: "CronJob",
    metadata: {},
    spec: {
      schedule: "*/5 * * * *",
      concurrencyPolicy: "Allow",
      suspend: false,
      successfulJobsHistoryLimit: 3,
      failedJobsHistoryLimit: 1,
      // startingDeadlineSeconds: 30,
      jobTemplate: {
        spec: {
          template: {}
        }
      }
    }
  }
})
const submit = (tag, autoCreateService)=> {
  console.log('tag:', tag)
  console.log('item:', useItemer.item)
  data.cronjobItem.spec.jobTemplate.spec.template = useItemer.item.spec.template
  data.cronjobItem.metadata = useItemer.item.metadata
  if (tag == 'yaml') {
    // 首先要把json转成yaml
    const yamlData = obj2Yaml(data.cronjobItem)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: useItemer.clusterId,
      namespace: useItemer.namespace,
      item: data.cronjobItem,
    }
    if (props.method != "Update") {
        // 创建用户，异步的
        createItem(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          // loading.value = false
          // emits('rollback')
          submitRollback(response.data.message)
        })
  } else {
      // 创建用户，异步的
      updateItem(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
      })
    }
  }

}
// 返回更新方式的类型
const concurrencyPolicy = [
      {
          value: "Allow",
          label: "允许并发调度"
      },
      {
          value: "Forbid",
          label: "禁止并发调度"
      },
      {
          value: "Replace",
          label: "替换上一次任务"
      }
  ]

const restartPolicy = [
    {
        value: "OnFailure",
        label: "失败时重启"
    },
    {
        value: "Never",
        label: "从不重启"
    },
]
onBeforeMount(()=>{
  useItemer.item.spec.template.spec.restartPolicy = 'OnFailure'
  //创建的时候需要添加吗？ 不需要
  if(props.method == "Create"){
   
    //删除副本数参数
    delete useItemer.item.spec.replicas
  } else {
    data.cronjobItem = props.cronJobItem
  }
}) 
const {clusterId, namespace,item} = storeToRefs(useItem())
const {cronjobItem} = toRefs(data)
</script>

<template>
<SchedulingFrame :method="props.method" 
  @submit="submit"
  :resource-type="props.resourceType">
      <template #strategy>
        <el-col :span="6">
              <el-form-item label="调度周期" prop="" >
                  <el-input v-model.trim="cronjobItem.spec.schedule" style="width: 180px;" />
              </el-form-item>
          </el-col>
          <el-col :span="6">
              <el-form-item label="并发策略" prop="cronjobItem.spec.concurrencyPolicy">
                  <el-select v-model="cronjobItem.spec.concurrencyPolicy" style="width: 180px;" placeholder="并发策略" >
                      <el-option
                      v-for="s in concurrencyPolicy"
                      :key="s.value"
                      :label="s.label"
                      :value="s.value"
                      />
                  </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="6">
              <el-form-item label="重启策略" prop="item.spec.template.spec.restartPolicy">
                  <el-select v-model="item.spec.template.spec.restartPolicy" style="width: 180px;" placeholder="并发策略" >
                      <el-option
                      v-for="s in restartPolicy"
                      :key="s.value"
                      :label="s.label"
                      :value="s.value"
                      />
                  </el-select>
              </el-form-item>
          </el-col>
         
          <el-col :span="6">
            <el-form-item label="暂停调度" prop="">
                <el-switch v-model="cronjobItem.spec.suspend"></el-switch>
            </el-form-item>
          </el-col>
        </template>
        <template #specialConfig>
          <el-col :span="6">
            <el-form-item label="失败任务保留数量" prop="cronjobItem.spec.failedJobsHistoryLimit">
              <el-input-number v-model="cronjobItem.spec.failedJobsHistoryLimit"  :min="1" ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="成功任务保留数量" prop="cronjobItem.spec.successfulJobsHistoryLimit">
              <el-input-number v-model="cronjobItem.spec.successfulJobsHistoryLimit"  :min="1" ></el-input-number>
            </el-form-item>
          </el-col>
        </template>
  </SchedulingFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  :method="props.method"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
</template>

<style scoped>

</style>